<script setup>
import { ref, onMounted } from 'vue';
import MapView from '../components/MapView.vue';
import ChatDialog from '../components/ChatDialog.vue';
import { runAgent, chatHistory } from '../agent';

const mapViewRef = ref(null);
const chatDialogRef = ref(null);
const isLoading = ref(false);

// 初始化时添加欢迎消息
onMounted(() => {
  addMessageToChat('您好！我是您的AI地图助手。我可以帮您在地图上绘制各种地理要素，比如标记点、路线和区域。请问有什么可以帮您的吗？', 'agent');
});

const addMessageToChat = (text, author) => {
  if (chatDialogRef.value) {
    chatDialogRef.value.addMessage({
      id: Date.now() + Math.random(),
      text,
      author, // 'user', 'agent', or 'thought'
      timestamp: new Date(),
    });
  }
};

const handleMessageSent = async (messageText) => {
  let t1 = new Date().getTime();
  addMessageToChat(messageText, 'user');
  isLoading.value = true;

  const mapTools = {
    drawPoint: (args) => mapViewRef.value?.drawPoint(args),
    drawPolyline: (args) => mapViewRef.value?.drawPolyline(args),
    drawPolygon: (args) => mapViewRef.value?.drawPolygon(args),
    clearMap: () => mapViewRef.value?.clearMap(),
    setMapView: (center, zoom) => mapViewRef.value?.setMapView(center, zoom),
  };

  const onIntermediateStep = (thought) => {
    addMessageToChat(thought, 'thought');
  };

  try {
    const finalResult = await runAgent(messageText, onIntermediateStep, mapTools);
    // 最多保留3条记录
    if (chatHistory.length >= 3) {
      chatHistory.shift();
    }
    chatHistory.push({ role: "user", content: messageText });
    chatHistory.push({ role: "assistant", content: finalResult });
    // 耗时多少秒
    let t2 = new Date().getTime();
    console.log(`耗时：${(t2 - t1) / 1000}秒`);
    addMessageToChat(finalResult, 'agent');
  } catch (error) {
    console.error("Error running agent:", error);
    addMessageToChat(`发生错误: ${error.message}`, 'agent');
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="home-container">
    <MapView ref="mapViewRef" class="map-view" />
    <ChatDialog 
      ref="chatDialogRef"
      :is-loading="isLoading"
      :floating="true"
      @message-sent="handleMessageSent"
      class="chat-dialog"
    />
  </div>
</template>

<style scoped>
.home-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.map-view {
  width: 100%;
  height: 100%;
}

.chat-dialog {
  position: absolute;
  z-index: 100;
}
</style>
